package com.lck.blogmanager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lck.blogmanager.Enum.CommonConstant;
import com.lck.blogmanager.entity.AdminEntity;
import com.lck.blogmanager.exception.BusinessException;
import com.lck.blogmanager.mapper.AdminMapper;
import com.lck.blogmanager.req.AdminLoginReq;
import com.lck.blogmanager.req.UpdateAdminInfoReq;
import com.lck.blogmanager.service.AdminService;
import com.lck.blogmanager.util.CacheTool;
import com.lck.blogmanager.util.PasswordEncodeUtil;
import com.lck.blogmanager.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/4/7 17:17
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminEntity> implements AdminService {

    private final CacheTool cacheTool;


    @Override
    public String adminLogin(AdminLoginReq req) {
        String telephone = req.getTelephone();
        String unCode = req.getPassword();
        String enCode = PasswordEncodeUtil.passwordEncode(unCode, CommonConstant.PASSWORD_SALT);
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdminEntity::getTelephone,telephone)
                .eq(AdminEntity::getPassword,enCode);
        AdminEntity entity = this.getBaseMapper().selectOne(wrapper);
        if(ObjectUtil.isNull(entity)){
            throw new BusinessException("管理员手机号或者密码错误");
        }
        Map<String,Object> payloads = new HashMap<>();
        payloads.put("userId",entity.getId());
        long l = System.currentTimeMillis() / 100 + CommonConstant.TOKEN_VALID_SECONDS;
        System.out.println(l);
        payloads.put("exp",l);
        String token = JWTUtil.createToken(payloads, CommonConstant.TOKEN_SIGN_KEY.getBytes());
        //加入缓存
        cacheTool.add(CommonConstant.TOKEN_PREFIX+entity.getId(),token);
        return token;
    }

    @Override
    public void resetPassword() {
        //获取用户id
        Integer adminId = SecurityUtils.getUserId();
        if(adminId==null){
            adminId = 1;
        }
        String encode = PasswordEncodeUtil.passwordEncode(CommonConstant.NORMAL_PASSWORD,CommonConstant.PASSWORD_SALT);
        AdminEntity entity = new AdminEntity();
        entity.setId(adminId);
        entity.setPassword(encode);
        int i = this.getBaseMapper().updateById(entity);
        if(i!=1){
            throw new BusinessException("重置管理员密码失败，请重试");
        }
    }

    @Override
    public void updateInfo(UpdateAdminInfoReq req) {
        //获取用户id
        Integer adminId = SecurityUtils.getUserId();
        //先判断老密码是不是对的不对的要报错
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdminEntity::getId,adminId);
        AdminEntity entity = this.getBaseMapper().selectOne(wrapper);
        if(ObjectUtil.isNull(entity)){
            throw new BusinessException("未知错误，找不到对应AdminId的管理员信息");
        }
        String enOldPwd = PasswordEncodeUtil.passwordEncode(req.getOldPassword(),CommonConstant.PASSWORD_SALT);
        if(!StrUtil.equals(enOldPwd,entity.getPassword())){
            throw new BusinessException("原密码不正确!");
        }
        String encode = PasswordEncodeUtil.passwordEncode(req.getNewPassword(),CommonConstant.PASSWORD_SALT);
        entity.setId(adminId);
        entity.setPassword(encode);
        int i = this.getBaseMapper().updateById(entity);
        if(i!=1){
            throw new BusinessException("修改管理员密码失败，请重试");
        }
    }

    @Override
    public AdminEntity adminInfo() {
        Integer id = null;
        id = SecurityUtils.getUserId();
        if(id==null){
            id = 1;
        }
        return this.getBaseMapper().selectById(id);
    }

}
